import { createRouter, createWebHistory } from 'vue-router'
import {useUserInfoStore} from "@/stores/user.js";
import {ElMessage} from "element-plus";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('@/views/layout/LayoutIndex.vue'),
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: () => import('@/views/home/HomeIndex.vue')
        },
        {
          path: '/category/:id',
          component: () => import('@/views/category/CategoryIndex.vue')
        },
        {
          path: '/category/:parId/:subId',
          component: () => import('@/views/category/SubCategory.vue')
        },
        {
          path: 'detail/:id',
          component: () => import('@/views/detail/DetailMain.vue')
        },
        {
          path: '/cart',
          component: () => import('@/views/cart/CartMain.vue')
        },
        {
          path: '/order',
          component: () => import('@/views/order/OrderIndex.vue')
        },
        {
          path: '/payment/:id',
          component: () => import('@/views/paypage/PayIndex.vue')
        },
        {
          path: '/paycallback', // 注意路径，必须是paycallback
          component: () => import('@/views/payback/PayBack.vue')
        },
        {
          path: '/user',
          component: () => import('@/views/user/UserCenter.vue'),
          redirect: '/info',
          children: [
            {
              path: '/info',
              component: () => import('@/views/user/components/UserInfo.vue')
            },
            {
              path: '/myorder',
              component: () => import('@/views/user/components/UserOrder.vue')
            }
          ]
        }
      ]
    },
    {
      path: '/login',
      component: () => import('@/views/login/LoginIndex.vue')
    }
  ],
  scrollBehavior: () => ({ top: 0 }),
})

const pathList = ['/order', '/cart']
router.beforeEach((to, from, next) => {
  const userStore = useUserInfoStore()
  if (pathList.includes(to.path)) {
    if (userStore.userInfo.token) {
      next()
    } else {
      ElMessage.warning('请先登录')
      next('/login')
    }
  } else {
    next()
  }
})


export default router
